package com.thinkTank.oa.perm;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.thinkTank.oa.common.UserInfo;
import com.thinkTank.oa.entity.LoginInfomation;
import com.thinkTank.oa.entity.Permission;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.service.LoginInfomationService;
import com.thinkTank.oa.service.PermissionService;
import com.thinkTank.oa.service.UserService;
import com.thinkTank.oa.util.StrUtil;

public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
	@Resource
	private UserService userService;
	@Resource
	private PermissionService permissionService;
	@Resource
	private LoginInfomationService loginInfomationService;
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
       
		/**
		 * 封装用户信息到session中
		 */
		UserDetails userDetails = (UserDetails)authentication.getPrincipal();
		//System.out.println("当前登录用户为"+userDetails.getUsername());
		User user = userService.getUserByUsername(userDetails.getUsername());
		UserInfo userInfo = new UserInfo();
		userInfo.setFullName(user.getFullName());
		userInfo.setUserId(user.getPid());
		request.getSession().setAttribute("userInfo", userInfo);
		
		try{
			LoginInfomation loginInfo = new LoginInfomation();
			loginInfo.setUserId(user.getPid());
			loginInfo.setLogindate(StrUtil.getCurrentDateTime_two());
			String ip = request.getHeader("x-forwarded-for");
			if(ip == null || ip.startsWith("196.168")||ip.equals("")){
			   ip = request.getRemoteAddr();
			}
			loginInfo.setIp(ip);
			loginInfomationService.add(loginInfo);
		}catch(Exception e){
			e.printStackTrace();
		}
		/**
		 * 加载用户菜单到session中
		 */
		List<Permission> per=permissionService.queryAllUserByPerm(user.getPid());
		request.getSession().setAttribute("userMenu", per);
        super.onAuthenticationSuccess(request, response, authentication);
        
    }
}



